Image classification is the most simple task in computer vision. Since convolutional networks started to gain traction among both computer vision researchers and practitioners, there has been many convolutional architectures developed to conquer the classification tasks. Nowadays, the most state-of-the-art architecture likely to achieve 90% accuracy in many cases. However, in real applications, many developers/practitioners build their own models that fit their tasks rather than relying on pre-trained architectures. Therefore, it is essential to understand the ideas, key structural changes that make an architecture better than another. In this project, I want to review 3 widely used convolutional architectures, namely Resnet, InceptionV3 network, and Xception network.
Specifically, I will measure the performance of those 3 models based on a real application: classify dog breeds. There are 133 categories of dog breeds in the dataset, which is collected from the ImageNet database. The challenges come from the complexity of the classification task (i.e. number of categories), many breeds of dog look very much alike. Therefore, we need a model not only sufficiently deep to learn the difference in details of each breed, but also techniques that help the model combat training difficulties, such as training time, exploding/vanishing gradient, overfitting and so on.
The models are evaluated based on the testing accuracy, i.e. percentage of correctly labeled images out of all testing images.
We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.
In the code cell below, we import a dataset of dog images. We populate a few variables through the use of the load_files function from the scikit-learn library:
train_files, valid_files, test_files - numpy arrays containing file paths to imagestrain_targets, valid_targets, test_targets - numpy arrays containing onehot-encoded classification labels dog_names - list of string-valued dog breed names for translating labels'''
Comment out the code below to install/downgrade Pillow to 5.4.1, and then restart the kernel
if there is an error saying:
"UnboundLocalError: local variable 'photoshop' referenced before assignment"
Ref: https://github.com/python-pillow/Pillow/pull/3771
'''
import PIL
PIL.__version__
# !pip install 'Pillow==5.4.1' --force-reinstall
TRAIN_DIR = '../../../data/dog_images/train'
VALID_DIR = '../../../data/dog_images/valid'
TEST_DIR = '../../../data/dog_images/test'
EPOCH = 5
BATCH_SIZE = 32
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg # for visualize images
from sklearn.datasets import load_files
from keras.utils import np_utils
from keras.callbacks import ModelCheckpoint
from glob import glob
from PIL import ImageFile, Image
ImageFile.LOAD_TRUNCATED_IMAGES = True
# define function to load train, test, and validation datasets
def load_dataset(path):
data = load_files(path)
dog_files = np.array(data['filenames'])
dog_targets = np_utils.to_categorical(np.array(data['target']), 133)
return dog_files, dog_targets
# load train, test, and validation datasets
train_files, train_targets = load_dataset(TRAIN_DIR)
valid_files, valid_targets = load_dataset(VALID_DIR)
test_files, test_targets = load_dataset(TEST_DIR)
# load list of dog names
dog_names = [item[20:-1] for item in sorted(glob(TRAIN_DIR+"/*/"))]
# print statistics about the dataset
print('There are %d total dog categories.' % len(dog_names))
print('There are %s total dog images.\n' % len(np.hstack([train_files, valid_files, test_files])))
print('There are %d training dog images.' % len(train_files))
print('There are %d validation dog images.' % len(valid_files))
print('There are %d test dog images.'% len(test_files))
In the code cell below, we import a dataset of human images, where the file paths are stored in the numpy array human_files.
import random
random.seed(8675309)
# load filenames in shuffled human dataset
human_files = np.array(glob("../../../data/lfw/*/*"))
random.shuffle(human_files)
# print statistics about the dataset
print('There are %d total human images.' % len(human_files))
for i in human_files[:5]:
img = Image.open(i)
print(f'Human Images of size {img.size}')
def display_images(files, nrow=2, ncol=3):
'''
Display images by nrow x ncol.
@param files: an array of paths of the images
'''
fig=plt.figure(figsize=(12, 8))
images = np.random.choice(files, ncol*nrow)
for i in range(0, ncol*nrow):
fig.add_subplot(nrow, ncol, i+1)
img = mpimg.imread(images[i])
labels = images[i].split('/')[-1]
plt.imshow(img)
plt.title(labels)
plt.show()
return
display_images(human_files)
Dog Images differ in sizes. Therefore we will need to crop to a fixed size for training our model later.
for i in train_files[:5]:
img = Image.open(i)
print(f'Dog Images of size {img.size}')
display_images(train_files)
We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github.
The next code cell demonstrate how to use this detector to find human faces in a sample image.
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')
# load color (BGR) image
img = cv2.imread(np.random.choice(human_files))
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# find faces in image
faces = face_cascade.detectMultiScale(gray)
# print number of faces detected in the image
print('Number of faces detected:', len(faces))
# get bounding box for each detected face
for (x,y,w,h) in faces:
# add bounding box to color image
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.
In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.
We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
return len(faces) > 0
Assess the Human Face Detector
Question 1: Use the code cell below to test the performance of the face_detector function.
human_files have a detected human face? dog_files have a detected human face? Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.
Answer:
human_files_short = human_files[:100]
dog_files_short = train_files[:100]
# Test the performance of the face_detector algorithm
# on the images in human_files_short and dog_files_short.
human_count = 0
dog_count = 0
for img in human_files_short:
human_count += face_detector(img)
for img in dog_files_short:
dog_count += face_detector(img)
print(f'Number of human faces detected in human files: {human_count}')
print(f'Number of human faces detected in dog files: {dog_count}')
Question 2: This algorithmic choice necessitates that we communicate to the user that we accept human images only when they provide a clear view of a face (otherwise, we risk having unneccessarily frustrated users!). In your opinion, is this a reasonable expectation to pose on the user? If not, can you think of a way to detect humans in images that does not necessitate an image with a clearly presented face?
Answer: It depends on the applications. For application that needs highly accurate detector, such as security, we should set requirements for our inputs. For application that is more of entertaining purposes, users would response negatively to the product if they are required to follow a set of rules. Therefore, we need to come up with an algorithm that can detect human faces in various situations, i.e. different angles, poses, emotions, light, and so on. In that case, not only we need a more diverse dataset, augment the dataset, but also a robust model that can be trained on a big input within reasonable time limit. That's where convolutional networks come in handy.
Here I'm using another version of haarcascades algorithms called haarcascade_frontalface_alt_tree, adopted from the same opencv github above.
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt_tree.xml')
human_count = 0
dog_count = 0
for img in human_files_short:
human_count += face_detector(img)
for img in dog_files_short:
dog_count += face_detector(img)
print(f'Number of human faces detected in human files: {human_count}')
print(f'Number of human faces detected in dog files: {dog_count}')
Results:
In this section, we use a pre-trained ResNet-50 model to detect dogs in images. Our first line of code downloads the ResNet-50 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories. Given an image, this pre-trained ResNet-50 model returns a prediction (derived from the available categories in ImageNet) for the object that is contained in the image.
from keras.applications.resnet50 import ResNet50
# define ResNet50 model
ResNet50_model = ResNet50(weights='imagenet')
When using TensorFlow as backend, Keras CNNs require a 4D array (which we'll also refer to as a 4D tensor) as input, with shape
$$ (\text{nb_samples}, \text{rows}, \text{columns}, \text{channels}), $$where nb_samples corresponds to the total number of images (or samples), and rows, columns, and channels correspond to the number of rows, columns, and channels for each image, respectively.
The path_to_tensor function below takes a string-valued file path to a color image as input and returns a 4D tensor suitable for supplying to a Keras CNN. The function first loads the image and resizes it to a square image that is $224 \times 224$ pixels. Next, the image is converted to an array, which is then resized to a 4D tensor. In this case, since we are working with color images, each image has three channels. Likewise, since we are processing a single image (or sample), the returned tensor will always have shape
The paths_to_tensor function takes a numpy array of string-valued image paths as input and returns a 4D tensor with shape
Here, nb_samples is the number of samples, or number of images, in the supplied array of image paths. It is best to think of nb_samples as the number of 3D tensors (where each 3D tensor corresponds to a different image) in your dataset!
from keras.preprocessing import image
from tqdm import tqdm
def path_to_tensor(img_path):
# loads RGB image as PIL.Image.Image type
img = image.load_img(img_path, target_size=(224, 224))
# convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)
x = image.img_to_array(img)
# convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor
return np.expand_dims(x, axis=0)
def paths_to_tensor(img_paths):
list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]
return np.vstack(list_of_tensors)
Getting the 4D tensor ready for ResNet-50, and for any other pre-trained model in Keras, requires some additional processing. First, the RGB image is converted to BGR by reordering the channels. All pre-trained models have the additional normalization step that the mean pixel (expressed in RGB as $[103.939, 116.779, 123.68]$ and calculated from all pixels in all images in ImageNet) must be subtracted from every pixel in each image. This is implemented in the imported function preprocess_input. If you're curious, you can check the code for preprocess_input here.
Now that we have a way to format our image for supplying to ResNet-50, we are now ready to use the model to extract the predictions. This is accomplished with the predict method, which returns an array whose $i$-th entry is the model's predicted probability that the image belongs to the $i$-th ImageNet category. This is implemented in the ResNet50_predict_labels function below.
By taking the argmax of the predicted probability vector, we obtain an integer corresponding to the model's predicted object class, which we can identify with an object category through the use of this dictionary.
from keras.applications.resnet50 import preprocess_input, decode_predictions
def ResNet50_predict_labels(img_path):
# returns prediction vector for image located at img_path
img = preprocess_input(path_to_tensor(img_path))
return np.argmax(ResNet50_model.predict(img))
While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained ResNet-50 model, we need only check if the ResNet50_predict_labels function above returns a value between 151 and 268 (inclusive).
We use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
prediction = ResNet50_predict_labels(img_path)
return ((prediction <= 268) & (prediction >= 151))
Assess the Dog Detector
Question 3: Use the code cell below to test the performance of your dog_detector function.
human_files_short have a detected dog? dog_files_short have a detected dog?Answer:
%%time
human_count = 0
dog_count = 0
for img in human_files_short:
human_count += dog_detector(img)
for img in dog_files_short:
dog_count += dog_detector(img)
print(f'Number of dog faces detected in human files: {human_count}')
print(f'Number of dog faces detected in dog files: {dog_count}')
We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have great difficulty in distinguishing between a Brittany and a Welsh Springer Spaniel.
| Brittany | Welsh Springer Spaniel |
|---|---|
![]() |
![]() |
It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).
| Curly-Coated Retriever | American Water Spaniel |
|---|---|
![]() |
![]() |
Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.
| Yellow Labrador | Chocolate Labrador | Black Labrador |
|---|---|---|
![]() |
![]() |
![]() |
We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.
ImageDataGenerator and flow_from_directory provide us a neat way to prepare train/valid/test set. For the training and validating generator, we use the same augmentation settings, while only normalize the testing generator.
from keras.preprocessing.image import ImageDataGenerator
# Define Generator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
width_shift_range=0.2,
height_shift_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
# only rescale in dev/test generator
valid_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
# Define train/dev/test sets
train_generator = train_datagen.flow_from_directory(
TRAIN_DIR,
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
color_mode="rgb",
shuffle=True,
seed=42
)
validation_generator = valid_datagen.flow_from_directory(
VALID_DIR,
target_size=(224, 224),
batch_size=32,
class_mode='categorical',
color_mode="rgb",
shuffle=True,
seed=42
)
test_generator = test_datagen.flow_from_directory(
TEST_DIR,
target_size=(224, 224),
batch_size=1,
class_mode=None, # no labels
color_mode="rgb",
shuffle=False, # no shuffling
seed=42
)
Model Architecture

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. If you chose to use the hinted architecture above, describe why you think that CNN architecture should work well for the image classification task.
Answer: The hinted architecture uses the convolutional blocks of the VGG architecture, however it is much smaller in size. I also use a dropout layer in each convolutional blocks to fight overfitting. The MaxPooling and GlobalAveragePooling layers not only can help reduce the computation expense but also turn out to be very good practice as pooling layers "filter out" the most important features/details (as with MaxPooling) or combine the effects of surrounding features (as with AveragePooling) in the image.
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.layers import Dropout, Flatten, Dense
from keras.models import Sequential
model = Sequential()
# Define your architecture.
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.3))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(GlobalAveragePooling2D())
model.add(Dropout(0.3))
# model.add(Flatten())
# model.add(Dense(256, activation='relu'))
# model.add(Dropout(0.5))
model.add(Dense(133, activation='softmax'))
model.summary()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Use model checkpointing to save the model that attains the best validation loss.
from keras.callbacks import ModelCheckpoint
epochs = 3
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.from_scratch.hdf5',
verbose=1, save_best_only=True)
model.fit_generator(
train_generator,
steps_per_epoch=500,
epochs=epochs,
validation_data=validation_generator,
validation_steps=200,
callbacks=[checkpointer],
verbose=1
)
model.load_weights('saved_models/weights.best.from_scratch.hdf5')
Try out your model on the test dataset of dog images. Ensure that your test accuracy is greater than 1%.
STEP_SIZE_TEST=test_generator.n//test_generator.batch_size
test_generator.reset()
pred = model.predict_generator(test_generator,
steps=STEP_SIZE_TEST,
verbose=1)
predicted_class_indices=np.argmax(pred,axis=1)
labels = (train_generator.class_indices)
labels = dict((v,k) for k,v in labels.items())
predictions = [labels[k] for k in predicted_class_indices]
# import pandas as pd
# filenames=test_generator.filenames
# results=pd.DataFrame({"Filename":filenames,
# "Predictions":predictions})
# get index of predicted dog breed for each image in test set
# dog_breed_predictions = [np.argmax(model.predict(np.expand_dims(tensor, axis=0))) for tensor in test_tensors]
# report test accuracy
test_accuracy = 100 * np.sum(np.array(predicted_class_indices)==np.argmax(test_targets, axis=1)) \
/ len(predicted_class_indices)
print('Test accuracy: %.4f%%' % test_accuracy)
bottleneck_features = np.load('bottleneck_features/DogVGG16Data.npz')
train_VGG16 = bottleneck_features['train']
valid_VGG16 = bottleneck_features['valid']
test_VGG16 = bottleneck_features['test']
The model uses the the pre-trained VGG-16 model as a fixed feature extractor, where the last convolutional output of VGG-16 is fed as input to our model. We only add a global average pooling layer and a fully connected layer, where the latter contains one node for each dog category and is equipped with a softmax.
VGG16_model = Sequential()
VGG16_model.add(GlobalAveragePooling2D(input_shape=train_VGG16.shape[1:]))
VGG16_model.add(Dense(133, activation='softmax'))
VGG16_model.summary()
VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
checkpointer = ModelCheckpoint(filepath='saved_models/weights.best.VGG16.hdf5',
verbose=1, save_best_only=True)
VGG16_model.fit(train_VGG16, train_targets,
validation_data=(valid_VGG16, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
VGG16_model.load_weights('saved_models/weights.best.VGG16.hdf5')
Now, we can use the CNN to test how well it identifies breed within our test dataset of dog images. We print the test accuracy below.
# get index of predicted dog breed for each image in test set
VGG16_predictions = [np.argmax(VGG16_model.predict(np.expand_dims(feature, axis=0))) for feature in test_VGG16]
# report test accuracy
test_accuracy = 100*np.sum(np.array(VGG16_predictions)==np.argmax(test_targets, axis=1))/len(VGG16_predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
from extract_bottleneck_features import *
def VGG16_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_VGG16(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = VGG16_model.predict(bottleneck_feature)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)]
for i, f in enumerate(test_files[:10]):
target_id = np.argmax(test_targets[i])
print(f'Dog class: {dog_names[target_id]}')
print(f'Predict: {VGG16_predict_breed(f)}')
print()
You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.
In Step 4, we used transfer learning to create a CNN using VGG-16 bottleneck features. In this section, you must use the bottleneck features from a different pre-trained model. To make things easier for you, we have pre-computed the features for all of the networks that are currently available in Keras:
The files are encoded as such:
Dog{network}Data.npz
where {network}, in the above filename, can be one of VGG19, Resnet50, InceptionV3, or Xception. Pick one of the above architectures, download the corresponding bottleneck features, and store the downloaded file in the bottleneck_features/ folder in the repository.
In the code block below, extract the bottleneck features corresponding to the train, test, and validation sets by running the following:
bottleneck_features = np.load('bottleneck_features/Dog{network}Data.npz')
train_{network} = bottleneck_features['train']
valid_{network} = bottleneck_features['valid']
test_{network} = bottleneck_features['test']
def build_bottleneck_model(model_path):
'''
Build CNN model using bottleneck features of pre-trained network.
Adding onto the bottleneck GlobalAveragePooling and a Fully Connected Network with 133 output labels.
Train and save the best model, then give the predictions based on it.
@param model_path: string, path to the bottleneck features
@return model: trained CNN model
@return predictions: predictions based on testing set
'''
# Obtain bottleneck features from another pre-trained CNN.
model_name = model_path.split('/')[-1]
bottleneck_features = np.load(model_path)
train = bottleneck_features['train']
valid = bottleneck_features['valid']
test = bottleneck_features['test']
# Define architecture.
model = Sequential()
model.add(GlobalAveragePooling2D(input_shape=train.shape[1:]))
model.add(Dropout(0.5))
model.add(Dense(133, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Train the model
checkpointer = ModelCheckpoint(filepath=f'saved_models/weights.best.{model_name}.hdf5',
verbose=1, save_best_only=True)
model.fit(train, train_targets,
validation_data=(valid, valid_targets),
epochs=20, batch_size=20, callbacks=[checkpointer], verbose=1)
# Load best model
model.load_weights(f'saved_models/weights.best.{model_name}.hdf5')
# Testing
predictions = [np.argmax(model.predict(np.expand_dims(feature, axis=0)))
for feature in test]
return model, predictions
Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.
Answer: Here I just use the pretrained InceptionV3 bottleneck, on top of which a GlobalAveragePooling and a softmax Dense layers are added to give the final probabilities for 133 classes. The InceptionV3 is a very deep network, using 42 layers, including Convolution, Max Pooling, Average Pooling. For a complex classification task like this, we may need such a deep model. More importantly, InceptionV3 offers a variety of brilliant techniques that help reduce the number of training parameters while still maintaining efficiency, such as Factorizing Convolution, Efficient Grid Size Reduction, and a regularization technique Auxiliary Classifier. Intuitively, it tells us whether the intermediate layers carry any important information, hence also help to avoid vanishing gradient. More details about InceptionV3.
InceptionV3_model, preds = build_bottleneck_model('bottleneck_features/DogInceptionV3Data.npz')
InceptionV3_model.summary()
# report test accuracy
test_accuracy = 100*np.sum(np.array(preds)==np.argmax(test_targets, axis=1)) \
/len(preds)
print('Test accuracy: %.4f%%' % test_accuracy)
# report test accuracy
model, predictions = build_bottleneck_model('bottleneck_features/DogResnet50Data.npz')
test_accuracy = 100*np.sum(np.array(predictions)==np.argmax(test_targets, axis=1)) \
/len(predictions)
print('Test accuracy: %.4f%%' % test_accuracy)
Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan_hound, etc) that is predicted by your model.
Similar to the analogous function in Step 5, your function should have three steps:
dog_names array defined in Step 0 of this notebook to return the corresponding breed.The functions to extract the bottleneck features can be found in extract_bottleneck_features.py, and they have been imported in an earlier code cell. To obtain the bottleneck features corresponding to your chosen CNN architecture, you need to use the function
extract_{network}
where {network}, in the above filename, should be one of VGG19, Resnet50, InceptionV3, or Xception.
from extract_bottleneck_features import *
def InceptionV3_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_InceptionV3(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = InceptionV3_model.predict(bottleneck_feature)
prob = np.max(predicted_vector)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)], prob
def Resnet_predict_breed(img_path):
# extract bottleneck features
bottleneck_feature = extract_Resnet50(path_to_tensor(img_path))
# obtain predicted vector
predicted_vector = model.predict(bottleneck_feature)
prob = np.max(predicted_vector)
# return dog breed that is predicted by the model
return dog_names[np.argmax(predicted_vector)], prob
for i, f in enumerate(test_files[:10]):
target_id = np.argmax(test_targets[i])
print(f'Dog class: {dog_names[target_id]}')
pred, prob = Resnet_predict_breed(f)
print(f'Predict: {pred} with {prob*100}% confidence')
print()
Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,
You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and dog_detector functions developed above. You are required to use your CNN from Step 5 to predict dog breed.
A sample image and output for our algorithm is provided below, but feel free to design your own user experience!

This photo looks like an Afghan Hound.
def detector(img_path):
'''
Build a detector, which gives predictions of a dog breed if the image contains either dog or human.
@param img_path: string, path to the input image
'''
has_human = face_detector(img_path)
has_dog = dog_detector(img_path)
pred, prob = InceptionV3_predict_breed(img_path)
pred = pred.split('.')[-1]
if has_human:
print("Human detected. Predicting ...")
print(f"Look likes: {pred} with {prob*100}% confidence")
if has_dog:
print("Dog detected. Predicting ...")
print(f"Breed: {pred} with {prob*100}% confidence")
if not has_human and not has_dog:
print("No human or dog detected. Please upload another image")
return
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def display_image(img_path):
img = mpimg.imread(img_path)
imgplot = plt.imshow(img)
plt.show()
return
for i, f in enumerate(human_files_short[:10]):
print(f'Human Image {i+1}')
display_image(f)
detector(f)
print()
for i, f in enumerate(dog_files_short[:10]):
print(f'Dog Image {i+1}')
display_image(f)
detector(f)
print()
In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?
Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.
Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.
Answer: The result is pretty good. Even though just 2 out of 5 dog images are classified correctly, the wrong ones are very challenging even for human. For example, Siberian Husky and Alaska Malamute are very much similar. Also, the model predicts with very high confidence, meaning it learned the features of the dog breeds. For future work, things that should be considered:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.
test_images = np.array(glob("images/test/*"))
for i, f in enumerate(test_images):
print(f'{i+1}: {test_images[i]}')
display_image(f)
detector(f)
print()